package com.tools.cleanmaster.manager;


import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.tools.cleanmaster.store.GlobalConfigSharedPrefManager;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;


public final class GlobalStateMgr {
    private static final String TAG = "GlobalStateMgr";

    private long mDid = -1;
    private boolean mToolboxNetDialogShown = false;

    private boolean mVersionLoaded = false;
    private String mVersionName;
    private int mVersionCode;

    private static GlobalStateMgr sInstance = new GlobalStateMgr();

    public static GlobalStateMgr getInstance() {
        return sInstance;
    }

    /**
     * When the application is quitting, call this method to clear some states.
     */
    public void onAppQuit() {
        mToolboxNetDialogShown = false;
    }

    /**
     * If no "did" saved, -1 will be returned.
     */
    public long getDid(Context cxt) {
        // TODO: need to care about multiple threads' calling?
        if (mDid == -1) {
            mDid = GlobalConfigSharedPrefManager.getDid(cxt);
        }
        return mDid;
    }

    public void updateDid(Context cxt, long newDid) {
        // TODO: need to care about multiple threads' calling?
        if (newDid <= 0) {
            if (FeatureConfig.DEBUG_LOG) LogHelper.w(TAG, "Bad did: " + newDid + ", discard it");
            return;
        }
        mDid = newDid;
        GlobalConfigSharedPrefManager.setDid(cxt, mDid);
    }

    public boolean isToolboxNetDialogShown() {
        return mToolboxNetDialogShown;
    }

    public void setToolboxNetDialogShown(boolean shown) {
        mToolboxNetDialogShown = shown;
    }

    private void loadVersionIfNeeded(Context cxt) {
        if (mVersionLoaded) {
            return;
        }

        try {
            PackageInfo pkgInfo = cxt.getPackageManager().getPackageInfo(cxt.getPackageName(), 0);
            mVersionName = pkgInfo.versionName;
            mVersionCode = pkgInfo.versionCode;
        } catch (NameNotFoundException e) {
            mVersionName = "";
            mVersionCode = 0;
        }
        mVersionLoaded = true;
    }

    public int getVersionCode(Context cxt, int defValue) {
        loadVersionIfNeeded(cxt);
        return mVersionLoaded ? mVersionCode : defValue;
    }

    public String getVersionName(Context cxt, String defValue) {
        loadVersionIfNeeded(cxt);
        return mVersionLoaded ? mVersionName : defValue;
    }

}
